package com.yusvn.scm.quartz.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.yusvn.scm.common.BaseController;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.ScmJob;
import com.yusvn.scm.common.model.ScmJobLog;
import com.yusvn.scm.quartz.service.ScmJobService;

/**
 * 定时任务
 * @author liugz
 */
public class ScmJobController extends BaseController {

	@Inject
	ScmJobService srv;
	
	public void index() {
		renderJson();
	}
	

	/**
	 * 手动执行一次
	 */
	public void runOneTask() {
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		kv.set("userid", getLoginUserId());
		
		renderJson(srv.runOneTask(kv) );
	}
	
	/**
	 * 启动
	 */
	public void addTask() {
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		kv.set("userid", getLoginUserId());
		
		renderJson(srv.addTask(kv) );
	}
	
	/**
	 * 停止
	 */
	public void removeTask() {
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		kv.set("userid", getLoginUserId());

		renderJson(srv.removeTask(kv) );
	}
	
	/**
	 * 查询
	 */
	public void page() {
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		kv.set("userid", getLoginUserId());
		
		Page<ScmJob> list = srv.page(kv);
		
		renderJson(RetKit.ok().setCount(list.getTotalRow()).setData( JSONObject.toJSON(list.getList()) ) );
	}
	
	/**
	 * 新增
	 */
	public void add() {
		renderJson(srv.add(getRawData()));
	}
	
	/**
	 * 修改
	 */
	public void update() {
        renderJson(srv.update(getRawData()));
	}
	
	/**
	 * 删除
	 */
	public void remove() {
		renderJson(srv.remove(getPara("id")));
	}
	
	/**
	 * 批量删除
	 */
	public void removeBatch(String idsStr) {
		renderJson(srv.removeBatch(getRawData() ) );
	}
	
	
	
	/**
	 * 获取定时任务运行日志
	 * @param kv
	 * @return
	 */
	public void getJobLog(){
		Kv kv = jsonStrToKv(getRawData());
		if(kv.isEmpty()) {
			kv = getKv();
		}
		// 获取当前登录用户
		kv.set("userid", getLoginUserId());
		
		Page<ScmJobLog> list = srv.getJobLog(kv);
		
		renderJson(RetKit.ok().setCount(list.getTotalRow()).setData( JSONObject.toJSON(list.getList()) ) );
	}
	
}
